// bookgo/borrow/borrow.js
Page({
  /**
   * 页面的初始数据
   */
    data: {
        openid:'',
        aid:'',
        reader_id:'',
        password:'',
        access_token:'',
        feiye_show:false,
        alert_show:false,
        input_code:'',
        isLogin:false, // 是否已经登录和绑定成功可以显示页面
        borrow_list:[],
        borrow_list_show: false,
        scan_borrow_list_show:false,
        scan_borrow_list:[],
        barcode_id:'',
        avatarUrl:'',
        appid:'',
        title:'',
        name:'',
        userInfo:[]
    },

  //跳转到添加/切换账号
    // changeUser: function () {        
    //         var that = this;
    //         that.getPassword();
    //         var openid = wx.getStorageSync('openid'),
    //             reader_id = wx.getStorageSync( that.data.aid + 'user').reader_id,
    //             password = that.data.password;
    //         wx.request({
    //             url: 'https://2016.bookgo.com.cn/wxapp/login/write',
    //             data: {
    //                 aid: that.data.aid,
    //                 reader_id: reader_id,
    //                 password: password,
    //                 openid: openid,
    //                 title:that.data.title,
    //                 name:that.data.userlist.name
    //             },
    //             success: function (res) {
    //                 console.log('------------whitecard--->res----------');
    //                 console.log(res);
    //                 wx.navigateTo({
    //                     url: '/bookgo/borrow/choose/choose?pid=' + res.data.msg + '&aid=' + that.data.aid
    //                 })
    //             }
    //         });       
    // },

    // getPassword: function () {
    //     var that = this;
    //     var aid = that.data.aid;
    //     var reader_id = wx.getStorageSync( that.data.aid + 'user').reader_id;
    //     console.log(reader_id);
    //     wx.request({
    //         url: 'https://2016.bookgo.com.cn/book/apiapp/get_password',
    //         data: {
    //             aid: aid,
    //             reader_id: reader_id
    //         },
    //         success: function (res) {
    //             if (res.data.code == 101) {
    //                 that.setData({
    //                     password: res.data.msg.password
    //                 })
    //             }
    //         }
    //     });
    // },

  //跳转到借阅记录
    myRecord: function () {
        var that = this;
        wx.navigateTo({
            url: '/bookgo/borrow/list/list?aid=' + that.data.aid,
        })
    },

  /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function (options) {
        var that = this;
        console.log('------Page onLoad函数---------');
        console.log('-----------------onLoad--->options--------------');
        console.log(options);
        var id = options.id;
        console.log('----------options.id------------');
        console.log(id);
        var thisaid = options.aid;
        console.log('----------------------aid---------------------');
        console.log(thisaid);

        if(thisaid){
            that.setData({
                aid: thisaid,
            });
        }

        if(id){
            that.setData({
                barcode_id:id
            });
        }
        if (id && !thisaid){
            wx.request({
                url: 'https://2016.bookgo.com.cn/book/api/get_barcode_by_id',
                data: {
                    id: id
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    wx.hideLoading();
                    console.log(res.data)
                    if (res.data.code == 101) {
                        that.setData({
                            aid: res.data.data.aid
                        })
                    }
                },
            })
        }
        if(!thisaid && !id){
            wx.redirectTo({
                url: '/bookgo/index/index',
            })
            return false;
        }
        // this.setData({
        //   barcode_id: 1
        // });
        
        // 如果是扫描借书二维码，则直接借阅成功
        wx.showLoading({
            title: '加载中',
        });
        that.go_login();
        that.loadData();
        // 获取openid并进行下一步       
    },

    
    loadData: function () {
        var that = this;    
        var userInfo = wx.getStorageSync('userInfo');
        console.log('--------------userInfo----------');
        console.log(userInfo);
        if (!userInfo) {
            wx.getUserInfo({
                success: function (res) {
                    console.log('-------wx.getUserInfo--------');
                    console.log(res);
                    that.setData({                  
                        avatarUrl: res.userInfo.avatarUrl
                    });
                    wx.setStorageSync('userInfo', res.userInfo);
                    console.log('+++++++++++++++++++wx.getStorageSync(user)++++++++++++++++++++');
                    var user = wx.getStorageSync( that.data.aid + 'user');
                    console.log(user);
                    wx.request({
                        url: 'https://2016.bookgo.com.cn/wxapp/login/userlist',
                        data: {
                            reader_id: user.reader_id,
                            aid: user.aid
                        },
                        header: {
                            'content-type': 'application/json'
                        },
                        success: function (res) {
                            console.log('----loadData-->success-->res-----');
                            console.log(res.data.msg);

                            that.setData({
                                name: res.data.msg.name,
                            });
                        }
                    })
                }
            })
        }else{
            that.setData({
                avatarUrl: userInfo.avatarUrl
            });
            console.log('+++++++++++++++++++wx.getStorageSync(user)++++++++++++++++++++');
            var user = wx.getStorageSync( that.data.aid + 'user');
            console.log(user);
            wx.request({
                url: 'https://2016.bookgo.com.cn/wxapp/login/userlist',
                data: {

                    reader_id: user.reader_id,
                    aid: user.aid
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    console.log('----loadData-->success-->res-----');
                    console.log(res.data.msg);

                    that.setData({
                        name: res.data.msg.name,
                    });
                }
            })
        }     
           
    },


    go_login(){
        console.log('logining..........');
        const that = this;
    //调用登录接口
        wx.login({
        success: function (e) {
            var openid = wx.getStorageSync('openid');
            if (!openid) {
            wx.request({
                url: 'https://2016.bookgo.com.cn/wxapp/index/login',
                data: {
                    code: e.code
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    console.log('+++++++++++获取openid++++++++++++++++');
                    console.log(res.data)
                    wx.setStorageSync('openid', res.data.openid)
                    that.check_bind(res.data.openid);
                },
                fail: function (res) {
                console.log(res)
                }
            })
            } else {
                that.check_bind(openid);
            }
                console.log('wxlogin successd........');
        }
        });
    },

    check_bind: function (openid) {
        const that = this;
        that.setData({
            openid: openid
        });
        // 判断是否有登录状态
        var user = wx.getStorageSync(that.data.aid + 'user');
        console.log('-----------判断是否有登录状态 user------------');
        console.log(that.data.aid);
        console.log(user.aid);
        console.log(user);
        if (!user) {
            if (that.data.aid) {
                // 获取图书馆名称
                that.get_lib_name(that.data.aid);
                console.log('开始获取用户信息');
                wx.request({
                url: 'https://2016.bookgo.com.cn/wxapp/api/check_bind',
                data: {
                    openid: openid,
                    aid: that.data.aid
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    console.log('-----------check_bind--->success--->res.data');
                    console.log(res.data)
                    if (res.data.code == 101) {
                        wx.setStorageSync('user', res.data.data);
                        that.login_success();
                    } else {
                        // 先判断aid是否已经存在了
                        if (that.data.aid) {
                            console.log('-----------走这边吗？-------------');
                            console.log(that.data.aid);
                                wx.redirectTo({
                                    url: '/bookgo/public_login/public_login?aid=' + that.data.aid,
                                });
                            }
                        }
                    },
                });
                // 将AID缓存下来
                wx.setStorage({
                key: 'myaid',
                data: that.data.aid,
                })
            } else {
                console.log('----get_aid_go_bind 1111--------');
                that.get_aid_go_bind(openid);
            }     
        } else {
            if(user.aid == that.data.aid){
                that.get_lib_name(that.data.aid);
                that.login_success();
                that.loadData();
            } else {
                // 先判断aid是否已经存在了                
                if (that.data.aid) {
                    console.log('---------------还是走这边？--------------');
                    console.log(that.data.aid);

                    wx.redirectTo({
                        url: '/bookgo/public_login/public_login?aid=' + that.data.aid,
                    });
                } else {
                    console.log('wwwww')
                    // 一定有barcode_id
                    // that.get_aid_go_public_login();
                    console.log('----get_aid_go_bind 2222--------');
                    that.get_aid_go_bind(openid);
                    that.loadData();
                }
            }       
        }
    },
    get_aid_go_bind: function (openid){
        wx.showLoading({
        title: '加载中',
        });
        var id = this.data.barcode_id;
        const that = this;
        wx.request({
        url: 'https://2016.bookgo.com.cn/book/api/get_barcode_by_id',
        data: {
            id: id
        },
        header: {
            'content-type': 'application/json'
        },
        success: function (res) {
            wx.hideLoading();
            console.log(res.data)
            if (res.data.code == 101) {
            var theaid = res.data.data.aid;
            wx.setStorage({
                key: 'myaid',
                data: res.data.data.aid,
            })

            console.log('开始获取用户信息');
            wx.request({
                url: 'https://2016.bookgo.com.cn/wxapp/api/check_bind',
                data: {
                    openid: openid,
                    aid: theaid
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    console.log(res.data)
                    if (res.data.code == 101) {
                        // 获取图书馆名称
                        that.setData({
                            aid:theaid
                        });
                        that.get_lib_name(theaid);

                        wx.setStorageSync('user', res.data.data);

                        that.login_success();
                } else {
                        console.log('-------------或者是走这边------------');
                        wx.redirectTo({
                            url: '/bookgo/public_login/public_login?aid=' + theaid,
                        });
                }
                },
                fail: function () {

                }
            })
            }
        },
        fail: function () {

        }
        })
    },
    get_lib_name:function(aid){  //获取图书馆名称
        wx.showLoading({
        title: '加载中',
        });
        const that = this;
        wx.request({
        url: 'https://2016.bookgo.com.cn/wxapp/api/get_lib_name',
        data: {
            aid: aid
        },
        header: {
            'content-type': 'application/json'
        },
        success: function (res) {
            wx.hideLoading();
            console.log('------get_lib_name-->success------');
            console.log(res.data)
            if (res.data.code == 101) {
            that.setData({
                title:res.data.data.title,
                appid:res.data.data.appid
            });
            wx.setNavigationBarTitle({
                title: res.data.data.title
            })
            }
        },
        fail: function () {

        }
        })
    },
    login_success(){
        
        wx.hideLoading();
        // this.get_borrow_list();
        this.go_barcode_id();
        this.setData({
            isLogin:true
        });
        // this.get_pic();
    },

    go_barcode_id(){
        wx.showLoading({
        title: '加载中',
        });
        var id = this.data.barcode_id;
        const that = this;
        wx.request({
            url: 'https://2016.bookgo.com.cn/book/api/get_barcode_by_id',
            data: {
                id: id
            },
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                wx.hideLoading();
                console.log(res.data)
                if (res.data.code == 101) {
                    var barcode = res.data.data.barcodes;
                    var theaid = res.data.data.aid;
                    var len = barcode.length;
                    if (barcode.substring(len - 1, len) == ','){
                        barcode = barcode.substring(0, len - 1)
                    }
                    var codes = barcode.split(',');
                    console.log(codes);
                    for(var i = 0; i < codes.length ; i ++){
                        that.go_borrow_with_lists(codes[i],theaid);
                    }
                }
            },
            fail: function () {

            }
        })
    },


    //扫码借书
    go_scan:function(){
        const that = this;
        var list = that.data.scan_borrow_list;
        list = [];
        that.data.scan_borrow_list = [];
        wx.scanCode({
        onlyFromCamera: true,
        success: (res) => {
            console.log('-------------go_scan--->success-----------');
            console.log(res);
            console.log(res.path);
            if (res.path) {
                // wx.redirectTo({
                //     url: '/' + res.path,
                // });
                var scene_data = res.path.split('?');
                var scene = decodeURIComponent(scene_data[1]);
                console.log(scene);
                var scene_data = scene.split(',');
                // console.log('-----------borrow scene_data-----------');
                // console.log(scene_data);
                if (scene_data[1]) {
                    that.setData({
                        barcode_id: scene_data[1]
                    });
                }
                that.go_barcode_id();
        
            } else {
            // 如果不是小程序码，则根据aid进行判断二维码规则，如果规则不符则不是资产码
            // http://2016.bookgo.com.cn/book/search/borrow1/appid/wx5beab4625197ba98
            console.log(that.data.appid)
            wx.navigateTo({
                url: '/bookgo/borrow/borrow_by_barcode/borrow_by_barcode?appid=' + that.data.appid + '&barcode=' + res.result,
            });
            // wx.showModal({
            //   title: '提示',
            //   content: '该二维码不是小程序码。',
            //   showCancel: false,
            //   success: function (res) {
            //     console.log(res);
            //   }
            // })
            }
        }
        });
    },
    //关闭扫码结果弹窗
    close_scan_borrow_list_show:function () {
        this.setData({
            scan_borrow_list_show:false
        
        })
    },
    go_borrow:function(code){
        wx.showLoading({
        title: '加载中',
        });
        console.log(code);
        var that = this;
        var user = wx.getStorageSync( that.data.aid + 'user'),
            reader_id = user.reader_id;
        // console.log(user);
        // console.log(code);return;
        wx.request({
            url: 'https://2016.bookgo.com.cn/book/search/do_brw_wxapp',
            data: {
                reader_id: reader_id,
                aid: that.data.aid,
                barcode:code
        },
        header: {
            'content-type': 'application/json'
        },
        success: function (res) {
            console.log('------------go_borrow--->success--->res----------');
            console.log(res.data);
            if(res.data.code == 0){
            wx.hideLoading();
            wx.showToast({
                title: '成功',
                icon: 'success',
                duration: 2000
            });
            //   that.get_borrow_list();
            }else{
            wx.hideLoading();
            wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel: false,
                success: function (res) {

                console.log(res);
                }
            })
            }
        },
        fail: function () {

        }
        })
    },  
    
    go_borrow_with_lists(code,theaid){
        const that = this;
        var reader_id = wx.getStorageSync( that.data.aid + 'user').reader_id;

        // var user = wx.getStorageSync( that.data.aid + 'user');
        wx.request({
        url: 'https://2016.bookgo.com.cn/book/search/do_brw_wxapp',
        data: {
            reader_id: reader_id,
            aid: theaid,
            barcode: code
        },
        header: {
            'content-type': 'application/json'
        },
        success: function (res) {
            console.log('---------------go_borrow_with_lists---------');
            console.log(res.data)
            var data = res.data;
            var item;
            if (res.data.code == 0) {
                item = {
                classname:'height:60px',
                bookname:data.bookname,
                barcode:data.barcode,
                isFail:false,
                isSuccess:true,
                msg:''
                };
            } else {
            var msg = res.data.message;
            var msg_data = msg.split(' ');
            console.log('=======================');
            console.log(msg_data);
            var mess_age = '';
                mess_age = msg_data[1];
            item = {
                classname: 'height:90px',
                bookname: data.bookname,
                barcode: data.barcode,
                isFail: true,
                isSuccess:false,
                msg: mess_age
            };
            }
            var list = that.data.scan_borrow_list;
            console.log('////**********///////')
            
            list.push(item)
            console.log('-------------list list list--------------');
            console.log(list);
            
            that.setData({
            scan_borrow_list: list
            });
            // 默认展示出来
            that.setData({
            scan_borrow_list_show: true,
            //   isFailaaa:true

            });
        },
        fail: function () {

        }
        })
    },

    input_code:function(e){
        console.log(e.detail.value)
        this.setData({
            input_code:e.detail.value
        });
    },
    input_borrow:function(){
        if (this.data.input_code != '') this.go_borrow(this.data.input_code);
    },




    shifou_go_logout:function () {
        var that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定退出？',
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                    that.go_logout();
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    },
    go_logout:function(){    
        const that = this;
        console.log(that.data.aid);
        var openid = wx.getStorageSync('openid');
        console.log(openid);
        wx.request({
            url: 'https://2016.bookgo.com.cn/wxapp/api/go_logout',
            data: {
                aid: that.data.aid,
                openid: openid
            },
            header: {
                'content-type': 'application/json'
            },
            success: function (res) {
                console.log(res.data)
                switch (res.data.code) {
                case 101:
                    wx.hideLoading();
                    
                    // wx.redirectTo({
                    //     url: '/bookgo/public_login/public_login',
                    // })
                    that.go_login();
                    that.loadData();
                    wx.clearStorageSync();
                    break;
                default:
                    wx.hideLoading();
                    wx.showModal({
                        title: '提示',
                        content: res.data.data,
                        showCancel: false,
                        success: function (res) {
                            console.log(res);
                        }
                    })
                }

            },
            fail: function () {

            }
        })
    },


    //   get_borrow_list(){
    //     const that = this;
    //     var user = wx.getStorageSync( that.data.aid + 'user');
    //     wx.request({
    //       url: 'https://2016.bookgo.com.cn/book/search/borrow_wxapp',
    //       data: {
    //         reader_id: user.reader_id,
    //         aid: user.aid
    //       },
    //       header: {
    //         'content-type': 'application/json'
    //       },
    //       success: function (res) {
    //         console.log(res.data)
    //         if (res.data.code == 101) {
    //           var listdata = res.data.data;
    //           // for(var i = 0; i < listdata.length ; i++){
    //           //   if (listdata[i].rfidstatus == 0)
    //           // }
    //           that.setData({
    //             borrow_list:listdata,
    //             borrow_list_show:true
    //           });
    //         //   console.log(that.data.borrow_list)
    //         } 
    //       },
    //       fail: function () {

    //       }
    //     })
    //   },
    //   show_feiye:function(e){
    //     if(e.target.id != 'tuli') return false;
    //     const that = this;
    //     that.setData({
    //       feiye_show: !that.data.feiye_show
    //     });
    //   },

    //   do_cancel(e){
    //     console.log(e.target.id);
    //     wx.showLoading({
    //       title: '请求中',
    //     });
    //     const that = this;
    //     wx.request({
    //       url: 'https://2016.bookgo.com.cn/book/search/borrow1_huan',
    //       data: {
    //         aid: that.data.aid,
    //         id: e.target.id
    //       },
    //       header: {
    //         'content-type': 'application/json'
    //       },
    //       success: function (res) {
    //         console.log(res.data)
    //         switch(res.data.code){
    //           case 101:
    //             wx.hideLoading();
    //             wx.showToast({
    //               title: '成功',
    //               icon: 'success',
    //               duration: 2000
    //             });
    //             // that.get_borrow_list();
    //             break;
    //           default:
    //             wx.hideLoading();
    //             wx.showModal({
    //               title: '提示',
    //               content: res.data.msg,
    //               showCancel: false,
    //               success: function (res) {
    //                 console.log(res);
    //               }
    //             })
    //         }

    //       },
    //       fail: function () {

    //       }
    //     })
    //   },

    //   go_mylist:function(){
    //     const that = this;
    //     wx.navigateTo({
    //       url: '/bookgo/borrow/mylist/mylist?aid=' + that.data.aid
    //     })
    //   },
    //   me_center:function(){
    //     console.log(this.data);
    //     const that = this;
    //     wx.showActionSheet({
    //       itemList: ['退出当前帐号'],
    //       success: function (res) {
    //         console.log(res.tapIndex)
    //         if (res.tapIndex == 0){
    //           that.go_logout();
    //         }
    //       },
    //       fail: function (res) {
    //         console.log(res.errMsg)
    //       }
    //     });

    //   },
    //   get_pic:function(){
    //     const that = this;
    //     // 先获取微信信息
    //     var userInfo = wx.getStorageSync('userInfo');
    //     if (!userInfo) {
    //       wx.getUserInfo({
    //         success: function (res) {
    //           console.log('wxgetUserInfo successd........');
    //           console.log(res.userInfo.avatarUrl);
    //           that.setData({
    //             avatarUrl: res.userInfo.avatarUrl
    //           });
    //           wx.setStorageSync('userInfo', res.userInfo);

    //         }
    //       })
    //     }
    //   },
    

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        // this.get_pic();
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('------Page onShow函数---------');
        
        this.loadData();
        // this.get_pic();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
    
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
    
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    //   onPullDownRefresh: function () {
    //     wx.showLoading({
    //       title: '加载中',
    //     });
    //     console.log('******')
    //     const that = this;
    //     var list = this.data.borrow_list;
    //     console.log('***1***')
    //     var re = [];
    //     for (var i = 0; i < list.length; i++) {
    //       var item = { barcode: list[i].barcode };
    //       re.push(item);
    //     }
    //     console.log('***2***')
    //     if (re.length == 0) {
    //       setTimeout(function(){
    //         wx.hideLoading();
    //       },1000);
    //       wx.stopPullDownRefresh()
    //       return false;
    //     }
    //     var user = wx.getStorageSync( that.data.aid + 'user');
    //     console.log('******')
    //     wx.request({
    //       url: 'https://2016.bookgo.com.cn/book/api/checkBooks_wxapp',
    //       method:'POST',
    //       data:{
    //         books: JSON.stringify(re),
    //           aid:that.data.aid
    //       },
    //       success: function (res) {
    //         wx.hideLoading();
    //         console.log(res)
    //         for (var i = 0; i < list.length; i++) {
    //           if(res.data.result[i].reader_id != user.reader_id || res.data.result[i].status != '借出'){
    //             list.splice(i,1);
    //           }
    //         }
    //         that.setData({
    //             borrow_list:list
    //         });
    //         wx.stopPullDownRefresh()
    //       }
    //     })
    //   },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
    
    }
})